# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import datetime
import json
import random
import re
import urllib2

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from wenlincms.utils.views import render

from mainsys.settings import elasticsearch_host, WEBSITE_CONF
from wlapps.utils.base62 import wlencode
from wlapps.utils.common import kongtostr
from wlmodels.codes.dicts import ex02_dict
from wlmodels.codes.models import ELNic, ELRegion, ELSeic, ELCA16
from wlmodels.company.models import ELPost, ELGeti, ELInv, ELManager, ELCaseDetail, ELPerson, ELModify, ELCaseBasic, \
    ELLicence, ELGetiLicence, ELMortReg, ELFiliation, ELStockContriFact, ELStockContriShould, ELStockFrost, \
    ELStockTransfer, \
    ELAnnualCheck, elasticsearch_index
from wlmodels.companyplus.models import ELFinanceTax, ELHGGoodsDetail
from wlviews.saas.fee import customer_verify_fee, noauth_redirct_url, saas_item_name, saas_item_fee, saas_item_faq
from wlviews.saas.models import ELSaasMsg, ELFeeLog, ELCustomerChargeLog
from wlviews.saas.utils import company_search_home_json


@never_cache
def index(request):
    # if "website_proxy" in WEBSITE_CONF and WEBSITE_CONF["website_proxy"]:
        # return HttpResponseRedirect("/accounts/login/")
    return render(request, "el_web/index.html", {})


@never_cache
def saas_index(request):
    enddate_1 = (datetime.datetime.now() - datetime.timedelta(30)).strftime("%Y-%m") + "-10"
    enddate_2 = (datetime.datetime.now() - datetime.timedelta(7)).strftime("%Y-%m-%d")
    randnum = int(datetime.datetime.now().strftime("%Y%m")) - 201600  # 随月份增加的一个随机数
    context = {"company_count": int(ELPost().get_total_count() / 10000),
               "geti_count": int(ELGeti().get_total_count() / 10000),
               "inv_manager_count": int((ELInv().get_total_count() + ELManager().get_total_count()) / 10000),
               "caiwu_count": int(ELFinanceTax().get_total_count() / 10000) + 6130 + int(randnum * 21.4),
               "case_count": int(ELCaseDetail().get_total_count() / 10000) + 1600 + int(randnum * 17.4),
               "enddate_1": enddate_1, "enddate_2": enddate_2,
               "company_zaiying": 2547 + int(randnum * 3.4),
               "geti_zaiying": 5574 + int(randnum * 7.4),
               "person_count": int(ELPerson().get_total_count() / 10000),
               "tax_count": int(ELFinanceTax().get_total_count() / 10000),
               "ac_count": int(ELAnnualCheck().get_total_count() / 10000),
               "hg_count": int(ELHGGoodsDetail().get_total_count() / 10000),
               "patent_count": 2332 + int(randnum * 23.3),
               "law_count": 2000 + int(randnum * 27.3),
               "alter_count": int(ELModify().get_total_count() / 10000),
               "entinv_count": 532 + int(randnum * 3.3),
               "personinv_count": 7000 + int(randnum * 13.3),
               "personposition_count": 7200 + int(randnum * 33.3),
               "case_base": int(ELCaseBasic().get_total_count() / 10000),
               "licence_count": int((ELLicence().get_total_count() + ELGetiLicence().get_total_count()) / 10000),
               "shixin_count": 600 + int(randnum * 11.3),
               "mort_count": float(ELMortReg().get_total_count()) / 10000,
               "filiation_count": int(ELFiliation().get_total_count() / 10000),
               "stockfact_count": int(ELStockContriFact().get_total_count() / 10000),
               "stockshould_count": int(ELStockContriShould().get_total_count() / 10000),
               "stockfrost_count": float(ELStockFrost().get_total_count()) / 10000,
               "stocktrans_count": int(ELStockTransfer().get_total_count() / 10000),
               "zb_count": 9000 + int(randnum * 72.3),
               "zp_count": 12000 + int(randnum * 172.3),
               "zzq_count": 3000 + int(randnum * 92.3),
               }
    return render(request, "saas/index.html", context)


@never_cache
def saas_index_for_java(request):
    enddate_1 = (datetime.datetime.now() - datetime.timedelta(30)).strftime("%Y-%m") + "-10"
    enddate_2 = (datetime.datetime.now() - datetime.timedelta(7)).strftime("%Y-%m-%d")
    randnum = int(datetime.datetime.now().strftime("%Y%m")) - 201600  # 随月份增加的一个随机数
    context = {"company_count": int(ELPost().get_total_count() / 10000),
               "geti_count": int(ELGeti().get_total_count() / 10000),
               "inv_manager_count": int((ELInv().get_total_count() + ELManager().get_total_count()) / 10000),
               "caiwu_count": int(ELFinanceTax().get_total_count() / 10000) + 6130 + int(randnum * 21.4),
               "case_count": int(ELCaseDetail().get_total_count() / 10000) + 1600 + int(randnum * 17.4),
               "enddate_1": enddate_1, "enddate_2": enddate_2,
               "company_zaiying": 2547 + int(randnum * 3.4),
               "geti_zaiying": 5574 + int(randnum * 7.4),
               "person_count": int(ELPerson().get_total_count() / 10000),
               "tax_count": int(ELFinanceTax().get_total_count() / 10000),
               "ac_count": int(ELAnnualCheck().get_total_count() / 10000),
               "hg_count": int(ELHGGoodsDetail().get_total_count() / 10000),
               "patent_count": 2332 + int(randnum * 23.3),
               "law_count": 2000 + int(randnum * 27.3),
               "alter_count": int(ELModify().get_total_count() / 10000),
               "entinv_count": 532 + int(randnum * 3.3),
               "personinv_count": 7000 + int(randnum * 13.3),
               "personposition_count": 7200 + int(randnum * 33.3),
               "case_base": int(ELCaseBasic().get_total_count() / 10000),
               "licence_count": int((ELLicence().get_total_count() + ELGetiLicence().get_total_count()) / 10000),
               "shixin_count": 600 + int(randnum * 11.3),
               "mort_count": float(ELMortReg().get_total_count()) / 10000,
               "filiation_count": int(ELFiliation().get_total_count() / 10000),
               "stockfact_count": int(ELStockContriFact().get_total_count() / 10000),
               "stockshould_count": int(ELStockContriShould().get_total_count() / 10000),
               "stockfrost_count": float(ELStockFrost().get_total_count()) / 10000,
               "stocktrans_count": int(ELStockTransfer().get_total_count() / 10000),
               "zb_count": 9000 + int(randnum * 72.3),
               "zp_count": 12000 + int(randnum * 172.3),
               "zzq_count": 3000 + int(randnum * 92.3),
               }
    return render(request, "saas/java_ui_index.html", context)


@never_cache
def new_saas_index(request):
    enddate_1 = (datetime.datetime.now() - datetime.timedelta(30)).strftime("%Y-%m") + "-10"
    enddate_2 = (datetime.datetime.now() - datetime.timedelta(7)).strftime("%Y-%m-%d")
    randnum = int(datetime.datetime.now().strftime("%Y%m")) - 201600  # 随月份增加的一个随机数
    context = {"company_count": int(ELPost().get_total_count() / 10000),
               "geti_count": int(ELGeti().get_total_count() / 10000),
               "inv_manager_count": int((ELInv().get_total_count() + ELManager().get_total_count()) / 10000),
               "caiwu_count": int(ELFinanceTax().get_total_count() / 10000) + 6130 + int(randnum * 21.4),
               "case_count": int(ELCaseDetail().get_total_count() / 10000) + 1600 + int(randnum * 17.4),
               "enddate_1": enddate_1, "enddate_2": enddate_2,
               "company_zaiying": 2547 + int(randnum * 3.4),
               "geti_zaiying": 5574 + int(randnum * 7.4),
               "person_count": int(ELPerson().get_total_count() / 10000),
               "tax_count": int(ELFinanceTax().get_total_count() / 10000),
               "ac_count": int(ELAnnualCheck().get_total_count() / 10000),
               "hg_count": int(ELHGGoodsDetail().get_total_count() / 10000),
               "patent_count": 2332 + int(randnum * 23.3),
               "law_count": 2000 + int(randnum * 27.3),
               "alter_count": int(ELModify().get_total_count() / 10000),
               "entinv_count": 532 + int(randnum * 3.3),
               "personinv_count": 7000 + int(randnum * 13.3),
               "personposition_count": 7200 + int(randnum * 33.3),
               "case_base": int(ELCaseBasic().get_total_count() / 10000),
               "licence_count": int((ELLicence().get_total_count() + ELGetiLicence().get_total_count()) / 10000),
               "shixin_count": 600 + int(randnum * 11.3),
               "mort_count": float(ELMortReg().get_total_count()) / 10000,
               "filiation_count": int(ELFiliation().get_total_count() / 10000),
               "stockfact_count": int(ELStockContriFact().get_total_count() / 10000),
               "stockshould_count": int(ELStockContriShould().get_total_count() / 10000),
               "stockfrost_count": float(ELStockFrost().get_total_count()) / 10000,
               "stocktrans_count": int(ELStockTransfer().get_total_count() / 10000),
               "zb_count": 9000 + int(randnum * 72.3),
               "zp_count": 12000 + int(randnum * 172.3),
               "zzq_count": 3000 + int(randnum * 92.3),
               }
    return HttpResponse(json.dumps(context), content_type='application/json')
    # return render(request, "saas/index.html", context)


# 企业多维筛查
@csrf_exempt
@never_cache
def saas_company_list(request):
    method = request.GET.get("method")
    if method == "loadtable":
        result = {"total": 0, "data": []}

        # 如果是本地开发环境，取本地数据
        # if not elasticsearch_host:
        #     for resobj in ELPost.objects.all()[:20]:
        #         dataobj = {"entid": wlencode(resobj.entid, addcrc=True),
        #                    "ENTNAME": kongtostr(resobj.ENTNAME),
        #                    "REGNO": kongtostr(resobj.REGNO),
        #                    "REGCAP": kongtostr(resobj.ent_basic.REGCAP),
        #                    "ESDATE": resobj.ent_basic.ESDATE.strftime("%Y-%m-%d") if resobj.ent_basic.ESDATE else "",
        #                    "nic_id": resobj.ent_class.nic_id.fulltitle if resobj.ent_class.nic_id else "",
        #                    "region_id": resobj.ent_class.region_id.fulltitle if resobj.ent_class.region_id else "",
        #                    "ENTTYPE": kongtostr(resobj.ent_basic.ENTTYPE),
        #                    "ENTSTATUS": kongtostr(resobj.ent_basic.get_ENTSTATUS_display()),
        #                    "elseic_id": "",
        #                    "OPSCOPE": kongtostr(resobj.ent_basic.OPSCOPE),
        #                    "enttel": kongtostr(resobj.ent_basic.TEL),
        #                    "faren": kongtostr(resobj.faren),
        #                    "farentel": kongtostr(resobj.farentel),
        #                    }
        #         result["data"].append(dataobj)
        #     result["total"] = len(result["data"])
        #     return HttpResponse(json.dumps(result), content_type="application/json")

        pageindex = int(request.POST['pageIndex']) if 'pageIndex' in request.POST else 0
        pagesize = int(request.POST['pageSize']) if 'pageSize' in request.POST else 20
        sortfield = request.POST['sortField'].strip() if 'sortField' in request.POST else ''
        sortorder = 'desc' if 'sortOrder' in request.POST and request.POST['sortOrder'] == 'desc' else 'asc'
        flag = 'sfield' in request.POST
        sfield = request.POST['sfield'].split("￥") if flag else []
        svalue = request.POST['svalue'].split("￥") if flag else []
        svalue = [x.strip() for x in svalue] if flag else []
        q_dict = {
            "query": {"bool": {}},
            "from": int(pageindex) * int(pagesize) if int(pageindex) * int(pagesize) <= 9000 else 9000,
            "size": int(pagesize)
        }
        q_url = elasticsearch_host + elasticsearch_index["company"] + "_search"

        # 如果是首页浏览，没有筛选和排序，取预设的结果
        # if sfield in [[""], []] and not sortfield and pageindex == 0 and pagesize == 20:
        #     return HttpResponse(json.dumps(company_search_home_json), content_type="application/json")

        # 如果有筛选
        if len(sfield) and len(sfield) == len(svalue):
            for i in xrange(len(sfield)):
                if svalue[i] in ["", None, "$"]:
                    continue
                # 模糊匹配
                if sfield[i] in ["ENTNAME", "OPSCOPE", ]:
                    querystring = {"match_phrase": {sfield[i]: svalue[i]}}
                    if "must" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["must"]):
                        q_dict["query"]["bool"]["must"].append(querystring)
                    elif len(svalue[i].strip()) > 1:
                        q_dict["query"]["bool"]["must"] = [querystring]
                # 前缀匹配
                elif sfield[i] in ["region_id", "nic_id", "elseic_id", "ENTTYPE"]:
                    new_v = svalue[i]
                    if sfield[i] == "ENTTYPE":
                        new_v = re.sub("0+$", "", new_v)
                    elif sfield[i] == "region_id":
                        new_v = re.sub("0{2,4}$", "", new_v)
                    querystring = {"prefix": {sfield[i]: new_v}}
                    if "filter" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["filter"]):
                        q_dict["query"]["bool"]["filter"].append(querystring)
                    else:
                        q_dict["query"]["bool"]["filter"] = [querystring]
                # 严格匹配
                elif sfield[i] in ["REGNO", "ENTSTATUS", ]:
                    if sfield[i] == "ENTSTATUS" and svalue[i] == "23":
                        querystring = {"terms": {sfield[i]: ["2", "3"]}}
                    else:
                        querystring = {"term": {sfield[i]: svalue[i]}}
                    if "filter" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["filter"]):
                        q_dict["query"]["bool"]["filter"].append(querystring)
                    else:
                        q_dict["query"]["bool"]["filter"] = [querystring]
                # 区间匹配
                elif sfield[i] in ["REGCAP", "ESDATE", "revenue", "total_profit", "assets_re", "timport", "texport", ]:
                    if "$" in svalue[i]:
                        new_v1 = svalue[i].split("$")[0]
                        new_v2 = svalue[i].split("$")[1]
                        if new_v1 and not new_v2:
                            querystring = {"range": {sfield[i]: {"gte": new_v1}}}
                        elif new_v2 and not new_v1:
                            querystring = {"range": {sfield[i]: {"lte": new_v2}}}
                        else:
                            querystring = {"range": {sfield[i]: {"gte": new_v1, "lte": new_v2}}}
                        if "filter" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["filter"]):
                            q_dict["query"]["bool"]["filter"].append(querystring)
                        else:
                            q_dict["query"]["bool"]["filter"] = [querystring]

        # 如果有排序
        if sortfield in ["REGCAP", "revenue", "total_profit", "assets_re", "timport", "texport", ]:
            q_dict["sort"] = {sortfield: {"order": sortorder}}

        q_json = json.dumps(q_dict).encode('utf8')
        req = urllib2.Request(url=q_url, data=q_json)
        res = urllib2.urlopen(req, timeout=120)
        res_data = res.read()
        res.close()
        res_dict = json.loads(res_data)
        result["total"] = res_dict["hits"]["total"]
        random.shuffle(res_dict["hits"]["hits"])
        # resfield用于控制返回字段列表的参数，主要控制是否返回财务相关字段，如果为空，则为全维筛查用的，需要返回法人和法人电话
        resfield = request.GET.get("resfield", None)
        for resobj in res_dict["hits"]["hits"]:
            the_entstatus, the_nic, the_region, the_enttype, = "", "", "", ""
            if resobj["_source"]["ENTSTATUS"] in dict(ex02_dict).keys():
                the_entstatus = dict(ex02_dict)[resobj["_source"]["ENTSTATUS"]]
            the_region = ELRegion.get_region(resobj["_source"]["region_id"], m="fulltitle")
            tmp = ELNic.objects.filter(code=resobj["_source"]["nic_id"]).first()
            if tmp:
                the_nic = tmp.fulltitle
            tmp = ELCA16.objects.filter(code=resobj["_source"]["ENTTYPE"]).first()
            if tmp:
                the_enttype = tmp.name
            if resfield == "1":
                dataobj = {"entid": wlencode(resobj['_source']["entid"], addcrc=True),
                           "ENTNAME": resobj["_source"]["ENTNAME"].split("。")[0],
                           "REGNO": kongtostr(resobj["_source"]["REGNO"]),
                           "revenue": int(resobj["_source"]["revenue"]) if resobj["_source"]["revenue"] else "",
                           "REGCAP": int(resobj["_source"]["REGCAP"]) if resobj["_source"]["REGCAP"] else "",
                           "assets_re": int(resobj["_source"]["assets_re"]) if resobj["_source"]["assets_re"] else "",
                           "ESDATE": kongtostr(resobj["_source"]["ESDATE"]),
                           "total_profit": int(resobj["_source"]["total_profit"]) if resobj["_source"][
                               "total_profit"] else "",
                           "nic_id": the_nic,
                           "region_id": the_region,
                           "ENTTYPE": the_enttype,
                           "ENTSTATUS": the_entstatus,
                           "elseic_id": "",
                           "OPSCOPE": kongtostr(resobj["_source"]["OPSCOPE"]),
                           "timport": kongtostr(resobj["_source"]["timport"]),
                           "texport": kongtostr(resobj["_source"]["texport"])
                           }
            else:
                entobj = ELPost.objects.filter(entid=resobj['_source']["entid"]).first()
                entobj = entobj if entobj else ELPost()
                dataobj = {"entid": wlencode(resobj['_source']["entid"], addcrc=True),
                           "ENTNAME": resobj["_source"]["ENTNAME"].split("。")[0],
                           "REGNO": kongtostr(resobj["_source"]["REGNO"]),
                           "REGCAP": int(resobj["_source"]["REGCAP"]) if resobj["_source"]["REGCAP"] else "",
                           "ESDATE": kongtostr(resobj["_source"]["ESDATE"]),
                           "nic_id": the_nic,
                           "region_id": the_region,
                           "ENTTYPE": the_enttype,
                           "ENTSTATUS": the_entstatus,
                           "elseic_id": "",
                           # "enttel": kongtostr(entobj.ent_basic.TEL),
                           "faren": kongtostr(entobj.faren),
                           "farentel": kongtostr(entobj.farentel),
                           "OPSCOPE": kongtostr(resobj["_source"]["OPSCOPE"])
                           }
            result["data"].append(dataobj)

        return HttpResponse(json.dumps(result), content_type="application/json")
    return render(request, "saas/companylist/index.html", {})


# 企业多维筛查 for java
@csrf_exempt
@never_cache
def saas_company_list_for_java(request):
    method = request.GET.get("method")
    if method == "loadtable":
        result = {"total": 0, "data": []}

        # 如果是本地开发环境，取本地数据
        # if not elasticsearch_host:
        #     for resobj in ELPost.objects.all()[:20]:
        #         dataobj = {"entid": wlencode(resobj.entid, addcrc=True),
        #                    "ENTNAME": kongtostr(resobj.ENTNAME),
        #                    "REGNO": kongtostr(resobj.REGNO),
        #                    "REGCAP": kongtostr(resobj.ent_basic.REGCAP),
        #                    "ESDATE": resobj.ent_basic.ESDATE.strftime("%Y-%m-%d") if resobj.ent_basic.ESDATE else "",
        #                    "nic_id": resobj.ent_class.nic_id.fulltitle if resobj.ent_class.nic_id else "",
        #                    "region_id": resobj.ent_class.region_id.fulltitle if resobj.ent_class.region_id else "",
        #                    "ENTTYPE": kongtostr(resobj.ent_basic.ENTTYPE),
        #                    "ENTSTATUS": kongtostr(resobj.ent_basic.get_ENTSTATUS_display()),
        #                    "elseic_id": "",
        #                    "OPSCOPE": kongtostr(resobj.ent_basic.OPSCOPE),
        #                    # "enttel": kongtostr(resobj.ent_basic.TEL),
        #                    "faren": kongtostr(resobj.faren),
        #                    "farentel": kongtostr(resobj.farentel),
        #                    }
        #         result["data"].append(dataobj)
        #     result["total"] = len(result["data"])
        #     return HttpResponse(json.dumps(result), content_type="application/json")

        pageindex = int(request.POST['pageIndex']) if 'pageIndex' in request.POST else 0
        pagesize = int(request.POST['pageSize']) if 'pageSize' in request.POST else 20
        sortfield = request.POST['sortField'].strip() if 'sortField' in request.POST else ''
        sortorder = 'desc' if 'sortOrder' in request.POST and request.POST['sortOrder'] == 'desc' else 'asc'
        flag = 'sfield' in request.POST
        sfield = request.POST['sfield'].split("￥") if flag else []
        svalue = request.POST['svalue'].split("￥") if flag else []
        svalue = [x.strip() for x in svalue] if flag else []
        q_dict = {
            "query": {"bool": {}},
            "from": int(pageindex) * int(pagesize) if int(pageindex) * int(pagesize) <= 9000 else 9000,
            "size": int(pagesize)
        }
        q_url = elasticsearch_host + elasticsearch_index["company"] + "_search"

        # 如果是首页浏览，没有筛选和排序，取预设的结果
        # if sfield in [[""], []] and not sortfield and pageindex == 0 and pagesize == 20:
        #     return HttpResponse(json.dumps(company_search_home_json), content_type="application/json")

        # 如果有筛选
        if len(sfield) and len(sfield) == len(svalue):
            for i in xrange(len(sfield)):
                if svalue[i] in ["", None, "$"]:
                    continue
                # 模糊匹配
                if sfield[i] in ["ENTNAME", "OPSCOPE", ]:
                    querystring = {"match_phrase": {sfield[i]: svalue[i]}}
                    if "must" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["must"]):
                        q_dict["query"]["bool"]["must"].append(querystring)
                    elif len(svalue[i].strip()) > 1:
                        q_dict["query"]["bool"]["must"] = [querystring]
                # 前缀匹配
                elif sfield[i] in ["region_id", "nic_id", "elseic_id", "ENTTYPE"]:
                    new_v = svalue[i]
                    if sfield[i] == "ENTTYPE":
                        new_v = re.sub("0+$", "", new_v)
                    elif sfield[i] == "region_id":
                        new_v = re.sub("0{2,4}$", "", new_v)
                    querystring = {"prefix": {sfield[i]: new_v}}
                    if "filter" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["filter"]):
                        q_dict["query"]["bool"]["filter"].append(querystring)
                    else:
                        q_dict["query"]["bool"]["filter"] = [querystring]
                # 严格匹配
                elif sfield[i] in ["REGNO", "ENTSTATUS", ]:
                    if sfield[i] == "ENTSTATUS" and svalue[i] == "23":
                        querystring = {"terms": {sfield[i]: ["2", "3"]}}
                    else:
                        querystring = {"term": {sfield[i]: svalue[i]}}
                    if "filter" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["filter"]):
                        q_dict["query"]["bool"]["filter"].append(querystring)
                    else:
                        q_dict["query"]["bool"]["filter"] = [querystring]
                # 区间匹配
                elif sfield[i] in ["REGCAP", "ESDATE", "revenue", "total_profit", "assets_re", "timport", "texport", ]:
                    if "$" in svalue[i]:
                        new_v1 = svalue[i].split("$")[0]
                        new_v2 = svalue[i].split("$")[1]
                        if new_v1 and not new_v2:
                            querystring = {"range": {sfield[i]: {"gte": new_v1}}}
                        elif new_v2 and not new_v1:
                            querystring = {"range": {sfield[i]: {"lte": new_v2}}}
                        else:
                            querystring = {"range": {sfield[i]: {"gte": new_v1, "lte": new_v2}}}
                        if "filter" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["filter"]):
                            q_dict["query"]["bool"]["filter"].append(querystring)
                        else:
                            q_dict["query"]["bool"]["filter"] = [querystring]

        # 如果有排序
        if sortfield in ["REGCAP", "revenue", "total_profit", "assets_re", "timport", "texport", ]:
            q_dict["sort"] = {sortfield: {"order": sortorder}}

        q_json = json.dumps(q_dict).encode('utf8')
        print q_json
        req = urllib2.Request(url=q_url, data=q_json)
        res = urllib2.urlopen(req, timeout=120)
        res_data = res.read()
        res.close()
        res_dict = json.loads(res_data)
        result["total"] = res_dict["hits"]["total"]
        random.shuffle(res_dict["hits"]["hits"])
        # resfield用于控制返回字段列表的参数，主要控制是否返回财务相关字段，如果为空，则为全维筛查用的，需要返回法人和法人电话
        resfield = request.GET.get("resfield", None)
        for resobj in res_dict["hits"]["hits"]:
            the_entstatus, the_nic, the_region, the_enttype, = "", "", "", ""
            if resobj["_source"]["ENTSTATUS"] in dict(ex02_dict).keys():
                the_entstatus = dict(ex02_dict)[resobj["_source"]["ENTSTATUS"]]
            # the_region = ELRegion.get_region(resobj["_source"]["region_id"], m="fulltitle")
            # tmp = ELNic.objects.filter(code=resobj["_source"]["nic_id"]).first()
            tmp=None
            if tmp:
                the_nic = tmp.fulltitle
            tmp = ELCA16.objects.filter(code=resobj["_source"]["ENTTYPE"]).first()
            if tmp:
                the_enttype = tmp.name
            if resfield == "1":
                dataobj = {"entid": wlencode(resobj['_source']["entid"], addcrc=True),
                           "ENTNAME": resobj["_source"]["ENTNAME"].split("。")[0],
                           "REGNO": kongtostr(resobj["_source"]["REGNO"]),
                           "revenue": int(resobj["_source"]["revenue"]) if resobj["_source"]["revenue"] else "",
                           "REGCAP": int(resobj["_source"]["REGCAP"]) if resobj["_source"]["REGCAP"] else "",
                           "assets_re": int(resobj["_source"]["assets_re"]) if resobj["_source"]["assets_re"] else "",
                           "ESDATE": kongtostr(resobj["_source"]["ESDATE"]),
                           "total_profit": int(resobj["_source"]["total_profit"]) if resobj["_source"][
                               "total_profit"] else "",
                           "nic_id": the_nic,
                           "region_id": the_region,
                           "ENTTYPE": the_enttype,
                           "ENTSTATUS": the_entstatus,
                           "elseic_id": "",
                           "OPSCOPE": kongtostr(resobj["_source"]["OPSCOPE"]),
                           "timport": kongtostr(resobj["_source"]["timport"]),
                           "texport": kongtostr(resobj["_source"]["texport"])
                           }
            else:
                # entobj = ELPost.objects.filter(entid=resobj["entid"]).first()
                entobj = ELPost.objects.filter(entid=resobj['_source']["entid"]).first()

                entobj = entobj if entobj else ELPost()
                dataobj = {"entid": wlencode(resobj['_source']["entid"], addcrc=True),
                           "ENTNAME": resobj["_source"]["ENTNAME"].split("。")[0],
                           # "REGNO": kongtostr(resobj["_source"]["REGNO"]),
                           "REGNO": "",
                           "REGCAP": int(resobj["_source"]["REGCAP"]) if resobj["_source"]["REGCAP"] else "",
                           "ESDATE": kongtostr(resobj["_source"]["ESDATE"]),
                           "nic_id": the_nic,
                           "region_id": the_region,
                           "ENTTYPE": the_enttype,
                           "ENTSTATUS": the_entstatus,
                           "elseic_id": "",
                           # "enttel": kongtostr(entobj.ent_basic.TEL),
                           "faren": kongtostr(entobj.faren),
                           "farentel": kongtostr(entobj.farentel),
                           "OPSCOPE": kongtostr(resobj["_source"]["OPSCOPE"])
                           }
            result["data"].append(dataobj)
            # 进行计费
            # if customer_verify_fee(request, saas_item="20", count=len(result["data"])):
            # result = {"total": 0, "data": []}
    return HttpResponse(json.dumps(result), content_type="application/json")
    # return render(request, "saas/companylist/index.html", {})


# 个体户多维筛查
@csrf_exempt
@never_cache
@login_required
def saas_geti_list(request):
    if customer_verify_fee(request, saas_pindao="10"):
        return HttpResponseRedirect(noauth_redirct_url)

    method = request.GET.get("method")
    if method == "loadtable":
        result = {"total": 0, "data": []}

        # 如果是本地开发环境，取本地数据
        if not elasticsearch_host:
            for resobj in ELGeti.objects.all()[:21]:
                the_nic = ""
                tmp = ELNic.objects.filter(code=(resobj.INDUSTRYPHY + resobj.INDUSTRYCO))
                if len(tmp):
                    the_nic = tmp[0].fulltitle
                the_region = ELRegion.get_region(resobj.OPLOCDISTRICT_id, m="fulltitle")
                dataobj = {"entid": resobj.entid,
                           "ENTNAME": kongtostr(resobj.ENTNAME),
                           "REGNO": kongtostr(resobj.REGNO),
                           "REGCAP": int(resobj.REGCAP),
                           "ESDATE": resobj.ESDATE.strftime("%Y-%m-%d") if resobj.ESDATE else "",
                           "nic_id": the_nic,
                           "region_id": the_region,
                           "ENTSTATUS": kongtostr(resobj.get_ENTSTATUS_display()),
                           "faren": kongtostr(resobj.faren),
                           "farentel": kongtostr(resobj.farentel),
                           "OPSCOPE": kongtostr(resobj.OPSCOANDFORM),
                           }
                result["data"].append(dataobj)
            result["total"] = len(result["data"])
            return HttpResponse(json.dumps(result), content_type="application/json")

        pageindex = int(request.POST['pageIndex']) if 'pageIndex' in request.POST else 0
        pagesize = int(request.POST['pageSize']) if 'pageSize' in request.POST else 20
        sortfield = request.POST['sortField'].strip() if 'sortField' in request.POST else ''
        sortorder = 'desc' if 'sortOrder' in request.POST and request.POST['sortOrder'] == 'desc' else 'asc'
        flag = 'sfield' in request.POST
        sfield = request.POST['sfield'].split("￥") if flag else []
        svalue = request.POST['svalue'].split("￥") if flag else []
        svalue = [x.strip() for x in svalue] if flag else []
        q_dict = {
            "query": {"bool": {}},
            "from": int(pageindex) * int(pagesize) if int(pageindex) * int(pagesize) <= 9000 else 9000,
            "size": int(pagesize)
        }
        q_url = elasticsearch_host + elasticsearch_index["geti"] + "_search"

        # 如果有筛选
        if len(sfield) and len(sfield) == len(svalue):
            for i in xrange(len(sfield)):
                if svalue[i] in ["", None, "$"]:
                    continue
                # 模糊匹配
                if sfield[i] in ["ENTNAME", "OPSCOPE"]:
                    querystring = {"match_phrase": {sfield[i]: svalue[i]}}
                    if "must" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["must"]):
                        q_dict["query"]["bool"]["must"].append(querystring)
                    elif len(svalue[i].strip()) > 1:
                        q_dict["query"]["bool"]["must"] = [querystring]
                # 前缀匹配
                elif sfield[i] in ["region_id", "nic_id", ]:
                    new_v = svalue[i]
                    if sfield[i] == "region_id":
                        new_v = re.sub("0{2,4}$", "", new_v)
                    querystring = {"prefix": {sfield[i]: new_v}}
                    if "filter" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["filter"]):
                        q_dict["query"]["bool"]["filter"].append(querystring)
                    else:
                        q_dict["query"]["bool"]["filter"] = [querystring]
                # 严格匹配
                elif sfield[i] in ["REGNO", "ENTSTATUS", ]:
                    if sfield[i] == "ENTSTATUS" and svalue[i] == "23":
                        querystring = {"terms": {sfield[i]: ["2", "3"]}}
                    else:
                        querystring = {"term": {sfield[i]: svalue[i]}}
                    if "filter" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["filter"]):
                        q_dict["query"]["bool"]["filter"].append(querystring)
                    else:
                        q_dict["query"]["bool"]["filter"] = [querystring]
                # 区间匹配
                elif sfield[i] in ["REGCAP", "ESDATE", ]:
                    if "$" in svalue[i]:
                        new_v1 = svalue[i].split("$")[0]
                        new_v2 = svalue[i].split("$")[1]
                        if new_v1 and not new_v2:
                            querystring = {"range": {sfield[i]: {"gte": new_v1}}}
                        elif new_v2 and not new_v1:
                            querystring = {"range": {sfield[i]: {"lte": new_v2}}}
                        else:
                            querystring = {"range": {sfield[i]: {"gte": new_v1, "lte": new_v2}}}
                        if "filter" in q_dict["query"]["bool"] and len(q_dict["query"]["bool"]["filter"]):
                            q_dict["query"]["bool"]["filter"].append(querystring)
                        else:
                            q_dict["query"]["bool"]["filter"] = [querystring]

        # 如果有排序
        if sortfield in ["REGCAP", ]:
            q_dict["sort"] = {sortfield: {"order": sortorder}}

        # 如果是首页浏览，没有筛选和排序，取随机数
        if sfield in [[""], []] and not sortfield and pageindex == 0:
            q_dict["from"] = random.randint(1, 20)

        q_json = json.dumps(q_dict).encode('utf8')
        req = urllib2.Request(url=q_url, data=q_json)
        res = urllib2.urlopen(req, timeout=120)
        res_data = res.read()
        res.close()
        res_dict = json.loads(res_data)
        result["total"] = res_dict["hits"]["total"]
        random.shuffle(res_dict["hits"]["hits"])
        for resobj in res_dict["hits"]["hits"]:
            the_entstatus, the_nic, the_region = "", "", ""
            if resobj["_source"]["ENTSTATUS"] in dict(ex02_dict).keys():
                the_entstatus = dict(ex02_dict)[resobj["_source"]["ENTSTATUS"]]
            the_region = ELRegion.get_region(resobj["_source"]["region_id"], m="fulltitle")
            tmp = ELNic.objects.filter(code=resobj["_source"]["nic_id"].replace("!", "")).first()
            if tmp:
                the_nic = tmp.fulltitle
            entobj = ELGeti.objects.filter(entid=resobj['_source']["entid"]).first()
            entobj = entobj if entobj else ELGeti()
            dataobj = {"entid": resobj['_source']["entid"],
                       "ENTNAME": resobj["_source"]["ENTNAME"],
                       "REGNO": kongtostr(resobj["_source"]["REGNO"]),
                       "REGCAP": kongtostr(resobj["_source"]["REGCAP"]),
                       "ESDATE": kongtostr(resobj["_source"]["ESDATE"]),
                       "nic_id": the_nic,
                       "region_id": the_region,
                       "ENTSTATUS": the_entstatus,
                       "faren": kongtostr(entobj.faren),
                       "farentel": kongtostr(entobj.farentel),
                       "OPSCOPE": kongtostr(resobj["_source"]["OPSCOPE"]),
                       }
            result["data"].append(dataobj)
        # 进行计费
        if customer_verify_fee(request, saas_item="20", count=len(result["data"])):
            result = {"total": 0, "data": []}
        return HttpResponse(json.dumps(result), content_type="application/json")
    return render(request, "saas/companylist/geti.html", {})


# 报告查询页
@never_cache
def saas_report_search(request):
    # if customer_verify_fee(request, saas_pindao="20"):
    # return HttpResponseRedirect(noauth_redirct_url)
    return render(request, "saas/reportsearch/search.html", {})


# 新的报告查询结果列表页（返回数据）
@csrf_exempt
@never_cache
def new_saas_search_result(request):
    context = {"selected": []}
    # 下面映射已选择的筛选条件
    svalue = request.GET.get('svalue')
    if svalue:
        svalue_list = svalue.split("￥")
        svalue_name = ["企业名称", "注册号", "地区", "行业", "产业", "状态", "类型", "主营业务", "注册资金", "开业日期", "员工人数", "营收", "利润", "资产",
                       "进口额", "出口额", ]
        if len(svalue_list) == 16:
            for i in range(16):
                if svalue_list[i] and svalue_list[i] != "$":
                    the_value = svalue_list[i]
                    if i == 2:
                        the_region = ELRegion.objects.filter(code=the_value).first()
                        if the_region:
                            the_value = the_region.fulltitle
                    elif i == 3:
                        the_nic = ELNic.objects.filter(code=the_value).first()
                        if the_nic:
                            the_value = the_nic.fulltitle
                    elif i == 4:
                        the_seic = ELSeic.objects.filter(code=the_value).first()
                        if the_seic:
                            the_value = the_seic.fulltitle
                    elif i == 5 and the_value in dict(ex02_dict).keys():
                        the_value = dict(ex02_dict)[the_value]
                    elif i == 6:
                        the_ca16 = ELCA16.objects.filter(code=the_value).first()
                        if the_ca16:
                            the_value = the_ca16.name
                    elif i > 7:
                        the_values = the_value.split("$")
                        if len(the_values) == 2 and the_values[0] and not the_values[1]:
                            the_value = "≥" + the_values[0]
                        elif len(the_values) == 2 and not the_values[0] and the_values[1]:
                            the_value = "≤" + the_values[1]
                        elif len(the_values) == 2 and the_values[0] and the_values[1]:
                            the_value = the_value.replace("$", "-")
                    context["selected"].append("%s: %s" % (svalue_name[i], the_value))
    return HttpResponse(json.dumps(context), content_type='application/json')
    # return render(request, "saas/reportsearch/result.html", context)


# 报告查询结果列表页
@csrf_exempt
@never_cache
def saas_search_result(request):
    context = {"selected": []}
    # 下面映射已选择的筛选条件
    svalue = request.GET.get('svalue')
    if svalue:
        svalue_list = svalue.split("￥")
        svalue_name = ["企业名称", "注册号", "地区", "行业", "产业", "状态", "类型", "主营业务", "注册资金", "开业日期", "员工人数", "营收", "利润", "资产",
                       "进口额", "出口额", ]
        if len(svalue_list) == 16:
            for i in range(16):
                if svalue_list[i] and svalue_list[i] != "$":
                    the_value = svalue_list[i]
                    if i == 2:
                        the_region = ELRegion.objects.filter(code=the_value).first()
                        if the_region:
                            the_value = the_region.fulltitle
                    elif i == 3:
                        the_nic = ELNic.objects.filter(code=the_value).first()
                        if the_nic:
                            the_value = the_nic.fulltitle
                    elif i == 4:
                        the_seic = ELSeic.objects.filter(code=the_value).first()
                        if the_seic:
                            the_value = the_seic.fulltitle
                    elif i == 5 and the_value in dict(ex02_dict).keys():
                        the_value = dict(ex02_dict)[the_value]
                    elif i == 6:
                        the_ca16 = ELCA16.objects.filter(code=the_value).first()
                        if the_ca16:
                            the_value = the_ca16.name
                    elif i > 7:
                        the_values = the_value.split("$")
                        if len(the_values) == 2 and the_values[0] and not the_values[1]:
                            the_value = "≥" + the_values[0]
                        elif len(the_values) == 2 and not the_values[0] and the_values[1]:
                            the_value = "≤" + the_values[1]
                        elif len(the_values) == 2 and the_values[0] and the_values[1]:
                            the_value = the_value.replace("$", "-")
                    context["selected"].append("%s: %s" % (svalue_name[i], the_value))
    # return HttpResponse(json.dumps(context), content_type='application/json')
    return render(request, "saas/reportsearch/result.html", context)


# 我的账户
@never_cache
@login_required
def saas_account_main(request):
    uc = request.user.u_ucenter
    the_msgs = ELSaasMsg.objects.all().order_by("-id")[:8]
    # 资费标准
    fee_cre = []
    for key in sorted(dict(saas_item_name).keys(), key=lambda x: int(x)):
        fee_cre.append({"name": dict(saas_item_name)[key], "fee": saas_item_fee[key], "faq": saas_item_faq[key]})
    context = {"uc": uc, "the_msgs": the_msgs, "fee_cre": fee_cre}
    return render(request, "saas/accounts/account_main.html", context)


# 消费和充值记录
@never_cache
@login_required
def saas_account_charge(request):
    uc = request.user.u_ucenter
    fpage = request.GET.get("fpage", 1)
    cpage = request.GET.get("cpage", 1)
    lookups = {"customer": request.user}
    # 时间区间筛选
    time = request.GET.get("sdate")
    time = time if time and "￥" in time else "￥"
    time_start = "" if not time.split("￥")[0] else datetime.datetime.strptime(time.split("￥")[0], "%Y-%m-%d")
    time_end = "" if not time.split("￥")[1] else datetime.datetime.strptime(time.split("￥")[1], "%Y-%m-%d")
    if time_start and time_start >= datetime.datetime.now() - datetime.timedelta(90):
        lookups["created__gte"] = time_start
    elif time_start and time_start < datetime.datetime.now() - datetime.timedelta(90):
        lookups["created__gte"] = datetime.datetime.now() - datetime.timedelta(90)
    if time_end and time_end <= datetime.datetime.now():
        lookups["created__lte"] = time_end
    fee_log = ELFeeLog.objects.filter(**lookups).order_by("-id")
    charge_log = ELCustomerChargeLog.objects.filter(**lookups).order_by("-id")
    # 控制页数，避免熊孩子故意设置很大的页码
    try:
        fpage = int(fpage) if fpage else 1
        fmax = int(fee_log.count() / 20) if fee_log.count() and (fee_log.count() % 20 == 0) else int(
            fee_log.count() / 20) + 1
        fpage = fmax if fpage > fmax else fpage
        cpage = int(cpage) if cpage else 1
        cmax = int(charge_log.count() / 20) if charge_log.count() and (charge_log.count() % 20 == 0) else int(
            charge_log.count() / 20) + 1
        cpage = cmax if cpage > cmax else cpage
    except:
        fpage, cpage = 1, 1
    context = {"uc": uc, "fee_log": fee_log[(fpage - 1) * 20:fpage * 20],
               "fpage_total": fee_log.count(), "charge_log": charge_log[(cpage - 1) * 20:cpage * 20],
               "cpage_total": charge_log.count(), }
    return render(request, "saas/accounts/account_charge.html", context)


# 我的机构
@never_cache
@login_required
def saas_account_org(request):
    return render(request, "saas/accounts/account_org.html", {})


# 征信授权
@never_cache
@login_required
def saas_account_sq(request):
    return render(request, "saas/accounts/account_sq.html", {})


# 异议数据
@never_cache
@login_required
def saas_account_yy(request):
    return render(request, "saas/accounts/account_yy.html", {})


# 无权限或余额不足时的跳转iframe
@never_cache
@login_required
def saas_account_noauth(request):
    return render(request, "saas/accounts/account_noauth.html", {})


# 地区和行业分类等的树表控件所需json
@csrf_exempt
@never_cache
# @login_required
def loadnode(request):
    result = []
    method = request.GET.get("method")
    code = request.POST['code'] if 'code' in request.POST else ''
    name = request.POST['name'].strip() if 'name' in request.POST else ''
    if method in ["nic", "region", "elnic", "elseic", "enttype"]:
        if method == "region":
            queryset = ELRegion.objects.all()
        elif method == "elseic":
            queryset = ELSeic.objects.all()
        elif method == "enttype":
            queryset = ELCA16.objects.all()
        else:
            queryset = ELNic.objects.all()
        if len(name) == 0:
            obj_result = queryset.filter(parent=code).order_by('code')
            if method == "enttype":
                for obj in obj_result:
                    if obj.code != "9999":
                        result.append({"id": obj.id, "code": obj.code, "parent": code,
                                       "level": obj.level, "name": obj.name, "isLeaf": False, "expanded": False})
            else:
                for obj in obj_result:
                    result.append({"id": obj.id, "code": obj.code, "parent": code, "fulltitle": obj.fulltitle,
                                   "level": obj.level, "name": obj.name, "isLeaf": False, "expanded": False})
            # 查看每个节点是否叶子节点
            for obj in result:
                child = queryset.filter(parent=obj['code']).order_by('code')
                if len(child):
                    obj['isLeaf'] = False
                    obj['expanded'] = False
                else:
                    obj['isLeaf'] = True
        else:
            obj_result = queryset.filter(name__icontains=name).order_by('code')
            if method == "enttype":
                for obj in obj_result:
                    result.append({"id": obj.id, "code": obj.code, "parent": "", "level": obj.level, "name": obj.name,
                                   "isLeaf": True, "expanded": False})
            else:
                for obj in obj_result:
                    result.append({"id": obj.id, "code": obj.code, "parent": "", "level": obj.level, "name": obj.name,
                                   "fulltitle": obj.fulltitle, "isLeaf": True, "expanded": False})
    return HttpResponse(json.dumps(result))


# 企业模糊搜索
@csrf_exempt
@never_cache
# @login_required
def entmohu(request):
    result = []
    if elasticsearch_host:
        the_key = request.POST['key'].strip() if 'key' in request.POST else ''
        if len(the_key) > 1:
            q_dict = {
                "query": {
                    "match_phrase": {"ENTNAME": the_key}
                },
                "terminate_after": 5
            }
            q_url = elasticsearch_host + elasticsearch_index["company"] + "_search"
            q_json = json.dumps(q_dict).encode('utf8')
            req = urllib2.Request(url=q_url, data=q_json)
            res = urllib2.urlopen(req, timeout=60)
            res_data = res.read()
            res.close()
            res_dict = json.loads(res_data)

            if res_dict["hits"]["hits"]:
                for resobj in res_dict["hits"]["hits"]:
                    result.append({"ENTNAME": resobj["_source"]["ENTNAME"].split("。")[0]})
    return HttpResponse(json.dumps(result))


# 个体户模糊搜索
@csrf_exempt
@never_cache
@login_required
def getimohu(request):
    result = []
    if elasticsearch_host:
        the_key = request.POST['key'].strip() if 'key' in request.POST else ''
        if len(the_key) > 1:
            q_dict = {
                "query": {
                    "match_phrase": {"ENTNAME": the_key}
                },
                "terminate_after": 5
            }
            q_url = elasticsearch_host + elasticsearch_index["geti"] + "_search"
            q_json = json.dumps(q_dict).encode('utf8')
            req = urllib2.Request(url=q_url, data=q_json)
            res = urllib2.urlopen(req, timeout=60)
            res_data = res.read()
            res.close()
            res_dict = json.loads(res_data)

            if res_dict["hits"]["hits"]:
                for resobj in res_dict["hits"]["hits"]:
                    result.append({"ENTNAME": resobj["_source"]["ENTNAME"]})
    return HttpResponse(json.dumps(result))
